Ext.define("jwawa.erp.common.AdvanceSearchWinHandler", {
    mixins:['jwawa.erp.framework.HandlerUtil'],
    ref: {
        searchGrpTreePanel: '#searchGrpTreePanel',
        addGrpButton:'#addGrpButton',
        delGrpButton: '#delGrpButton',
        setDefaultGrpButton: '#setDefaultGrpButton',
        searchGrpToolbar: '#searchGrpToolbar',
        editingSearchGrpToolbar: '#editingSearchGrpToolbar',
        saveSearchItemButton: '#saveSearchItemButton',
        addSearchItemButton: '#addSearchItemButton',
        closeAdvanceSearchWinButton: '#closeAdvanceSearchWinButton',
        searchAdvanceSearchButton: '#searchAdvanceSearchButton',
        searchItemPanel: '#searchItemPanel',
        emptySearchItemButton: '#emptySearchItemButton',

        searchPanel: function(){
            return this.view.searchPanel;
        },
        cellEditing: function(){
            return this.searchGrpTreePanel.getPlugin('cellplugin');
        },
        rootNode: function(){
            return this.searchGrpTreePanel.getStore().getRootNode();
        }
    },
    constructor: function(params){
        "use strict";
        Ext.apply(this, params);

    },

    bindHandler: function(){
        "use strict";
        var me = this,
            view = me.view,
            ref = me.ref;

        me.initRef(view, ref);

        me.currentSearchGroupId = null;
        me.defaultSearchGroup = null;
        me.pleaseInputStr = '请输入名称...';

        view.on('hide', me.onHideAdvanceSearchWin, me);

        me.initSearchGroupPanel();
        me.initSearchItemPanel();
        me.disableButtonState();
    },

    initSearchGroupPanel: function(){
        "use strict";
        var me = this,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        commonSearchModel.searchGroupStore.each(function(searchGroup){
            if(searchGroup.get('id') == 0){
                return;
            }
            var node = me.rootNode.appendChild({
                id: searchGroup.get('id'),
                text: searchGroup.get('group_name'),
                is_default: searchGroup.get('is_default'),
                seq : searchGroup.get('seq'),
                iconCls: (searchGroup.get('is_default') === 'Y' ? 'search-group-default-icon' : 'search-group-icon'),
                leaf: true
            });

//            if(node.raw.is_default === 'Y'){
//                me.defaultSearchGroup = node;
//            }

            if(searchGroup.get('is_default') === 'Y'){
                me.defaultSearchGroup = node;
            }
        });

        me.searchGrpTreePanel.on('itemclick', me.onItemClickSelectSearchGroup, me);
        me.searchGrpTreePanel.on('canceledit', me.onCancelEditSearchGroupCell, me);
        me.searchGrpTreePanel.on('edit', me.onEditSearchGroupCell, me);
        me.addGrpButton.on('click', me.onClickAddSearchGroupBtn, me);
        me.delGrpButton.on('click', me.onClickDeleteSearchGroupBtn, me);
        me.setDefaultGrpButton.on('click', me.onClickSetDefaultSearchGroupBtn, me);
    },

    initSearchItemPanel: function(){
        "use strict";
        var me = this;

        me.addSearchItemButton.on('click', me.onClickAddSearchItemBtn, me);
        me.emptySearchItemButton.on('click', me.onClickEmptySearchItemBtn, me);
        me.saveSearchItemButton.on('click', me.onClickSaveSearchItemBtn, me);
        me.closeAdvanceSearchWinButton.on('click', me.onClickCloseWinBtn, me);

        me.searchAdvanceSearchButton.on('click', me.onClickAdvanceSearchBtn, me);
    },

    onItemClickSelectSearchGroup: function(obj, record, item, index, e, eOpts ){
        "use strict";
        var me = this,
            groupId = record.getId();

        me.currentSearchGroupId = groupId;
        me.resetSearchItemPanelByGroupId(groupId);
        me.enableButtonState();
    },

    resetSearchItemPanelByGroupId: function(searchGroupId){
        "use strict";
        var me = this,
            searchGroupItemShipList,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        if(!Ext.isEmpty(searchGroupId)){
            me.searchItemPanel.removeAll();
            searchGroupItemShipList = commonSearchModel.getSearchGroupItemShipListByGroupId(searchGroupId);

            Ext.Array.forEach(searchGroupItemShipList, function(searchGroupItemShip){
                me.addSearchItemFieldContainer(searchGroupItemShip);
            });

        }
    },

    onClickAddSearchItemBtn: function(){
        "use strict";
        var me = this;

        me.addSearchItemFieldContainer(null);
    },

    addSearchItemFieldContainer: function(searchGroupItemShip){
        "use strict";
        var me = this,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel'),
            item;

        if(commonSearchModel.searchItemStore.getCount() === 0){
            return null;
        }

        if (Ext.isEmpty(searchGroupItemShip)){
            item = commonSearchModel.searchItemStore.getAt(0);
            searchGroupItemShip = {
                search_group_id: me.currentSearchGroupId,
                search_item_id: item.get('id'),
                seq: 1
            }
        }

        var fieldContainer = me.createSearchItemFieldContainer(searchGroupItemShip);
        me.searchItemPanel.add(fieldContainer);

        return fieldContainer;
    },

    createSearchItemFieldContainer: function(searchGroupItemShip){
        "use strict";
        var me = this,
            fieldContainer,
            searchItemComboBox,
            itemCfg,
            itemInputCtrl,
            delItemBtn,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel'),
            searchItemStore = commonSearchModel.searchItemStore,
            searchItemRec = commonSearchModel.searchItemStore.getById(searchGroupItemShip['search_item_id']);

            fieldContainer = Ext.create('Ext.form.FieldContainer',{
            layout: {
                align: 'stretch',
                type: 'hbox'
            },
            hideLabel: true,
            fieldDefaults: {
                margin: '0 2 0 0'
            }
        });

        searchItemComboBox = Ext.create('Ext.form.ComboBox',{
            itemId: 'itemSelectField',
            queryMode: 'local',
            displayField: 'entity_field_label',
            valueField: 'id',
            flex: 1,
            hideLabel: true,
            editable : false,
            allowBlank: false,
            store: searchItemStore,
            listeners:{
                select: Ext.bind(me.onSelectSearchItemCombox, me)
            }
        });

        searchItemComboBox.setValue(searchGroupItemShip['search_item_id']);
        fieldContainer.add(searchItemComboBox);

        itemCfg = me.makeItemDefaultValueFieldCfg(searchGroupItemShip);
        itemInputCtrl = Ext.create(searchItemRec.get('item_class'), itemCfg);
        fieldContainer.add(itemInputCtrl);

        delItemBtn = Ext.create('Ext.Button',{
            width: 23,
            margin: '0 2 0 0',
            icon: '/img/trash.gif',
            handler: Ext.bind(me.deleteSearchItemContainer, me)
        });

        fieldContainer.add(delItemBtn);

        return fieldContainer;
    },

    onHideAdvanceSearchWin: function(){
        "use strict";
        var me = this;

        me.searchPanel.down('#searchGroupCombobox').setValue(0);
    },

    onEditSearchGroupCell: function(editor, e, eOpts ){
        "use strict";
        var me = this,
            searchGroup,
            sm = me.searchGrpTreePanel.getSelectionModel(),
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        if(e.record.get(e.field) === me.pleaseInputStr){
            e.record.remove();
            return;
        }

        if (e.record.modified[e.field] == null){
            return;
        }

        searchGroup =  {
            'page_code': me.searchPanel.pageCode,
            'id': e.record.get('id'),
            'group_name': e.record.get('text')
        };

        Ext.Ajax.useDefaultErrorAlert = false;
        commonSearchModel.saveSearchGroup(searchGroup, {
            success: function(searchGroup){
                e.record.setId(searchGroup['id']);
                e.record.set('seq', searchGroup['seq']);
                e.record.commit();
                sm.deselectAll();

                sm.select(e.record);
                me.currentSearchGroupId = searchGroup['id'];
                me.enableButtonState();
            },
            failure: function(response){
                alertError(response.message, function(){
                    me.cellEditing.startEdit(e.record, e.column);
                });
            }
        });
        Ext.Ajax.useDefaultErrorAlert = true;
    },

    onClickAddSearchGroupBtn: function(){
        "use strict";
        var me = this;

        var newGrp = me.rootNode.appendChild({
            text:  me.pleaseInputStr,
            iconCls: 'search-group-icon',
            leaf: true
        });

        me.searchItemPanel.removeAll();
        me.cellEditing.startEdit(newGrp, me.searchGrpTreePanel.columns[0]);
    },

    onClickDeleteSearchGroupBtn: function(){
        "use strict";
        var me = this,
            deleteSearchGroupIdList = [],
            sm = me.searchGrpTreePanel.getSelectionModel(),
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        var currentSelectionList = sm.getSelection();
        if(sm.getSelection().length >= 1){
            me.disableButtonState();
            me.currentSearchGroupId = null;
            sm.deselectAll();

            for(var i = 0; i < currentSelectionList.length; i++){
                deleteSearchGroupIdList[i] = currentSelectionList[i].getId();
            }

            commonSearchModel.deleteSearchGroup(deleteSearchGroupIdList, function(){
                for(var i = 0; i < deleteSearchGroupIdList.length; i++){
                    currentSelectionList[i].remove();
                }
                me.searchItemPanel.removeAll();
            });
        }
    },

    disableButtonState: function(){
        var me = this;

        me.delGrpButton.disable();
        me.saveSearchItemButton.disable();
        me.setDefaultGrpButton.disable();
    },

    enableButtonState: function(){
        var me = this;

        me.delGrpButton.enable();
        me.saveSearchItemButton.enable();
        me.setDefaultGrpButton.enable();
    },

    onClickSetDefaultSearchGroupBtn: function(){
        "use strict";
        var me = this,
            sm = me.searchGrpTreePanel.getSelectionModel(),
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        if(sm.getSelection().length === 1){
            var tmpSelect =  sm.getSelection()[0],
                newDefaultGroupId = tmpSelect.getId();

            commonSearchModel.setDefaultSearchGroup(newDefaultGroupId, function(){
                    if(me.defaultSearchGroup){
                        me.defaultSearchGroup.set('iconCls', 'search-group-icon');
//                        me.defaultSearchGroup.raw.is_default = 'N';
                        me.defaultSearchGroup.set('is_default', 'N');
                    }

                    me.defaultSearchGroup = tmpSelect;
//                    tmpSelect.raw.is_default = 'Y';
                    tmpSelect.set('is_default', 'Y');
                    tmpSelect.set({'iconCls': 'search-group-default-icon'});
//                  me.searchGrpTreePanel.getView().addRowCls(me.defaultSearchGroup, 'x-grid-row-selected' );
                    sm.deselectAll();
                    sm.select(tmpSelect);
            });
        }
    },

    onCancelEditSearchGroupCell: function(editor, e, eOpts){
        "use strict";
        var me = this;

        if(e.record.dirty){
            e.record.reject();
        }

        if(Ext.String.trim(e.record.get(e.field)) === me.pleaseInputStr){
            e.record.remove();
        }
    },

    onClickAdvanceSearchBtn: function(){
        "use strict";
        var me = this,
            searchItemList;

        var serchItemCombobox = me.checkDuplicateSearchItem();
        if(serchItemCombobox){
            alertError('[' + serchItemCombobox.getDisplayValue() + '] 重复，无法提交查询');
            return;
        }

        if(!me.searchItemPanel.getForm().isValid()){
            return;
        }

        me.view.hide();
        searchItemList = me.gatherSearchItemListFromAdvPanel();
        me.searchPanel.handler.resetSearchPanel(searchItemList);
        me.searchPanel.handler.onClickSearchButton();
    },

    gatherSearchItemListFromAdvPanel: function(){
        "use strict";
        var me = this,
            fdList,
            searchGroupItemShipList = [];

        fdList= Ext.ComponentQuery.query('fieldcontainer', me.searchItemPanel);
        for(var i = 0; i < fdList.length; i++){
            var itemId = fdList[i].down('#itemSelectField').getValue();
            var itemValue = fdList[i].down('#itemDefaultValueField').getValue();
            var searchGroupItemShip = {
                search_group_id: me.currentSearchGroupId,
                search_item_id:  itemId,
                default_value: itemValue,
                seq: i + 1
            };

            searchGroupItemShipList.push(searchGroupItemShip);
        }

        return searchGroupItemShipList;
    },

    onClickCloseWinBtn: function(){
        "use strict";
        var me = this;
        me.view.hide();
    },

    onClickSaveSearchItemBtn: function(){
        "use strict";
        var me = this,
            sarchGroupItemShipList,
            serchItemCombobox,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        serchItemCombobox = me.checkDuplicateSearchItem();
        if(serchItemCombobox){
            alertError('[' + serchItemCombobox.getDisplayValue() + '] 重复，无法保存');
            return;
        }

        sarchGroupItemShipList = me.gatherSearchItemListFromAdvPanel();
        me.view.setLoading(true);
        commonSearchModel.saveSearchGroupItemShip(me.currentSearchGroupId,
            sarchGroupItemShipList, {
                success: function(){
                    top.msgBar.showSuccessMsg('自定义查询条件保存成功');
                },
                callback: function(){
                    me.view.setLoading(false);
                }
            });
    },

    checkDuplicateSearchItem: function(){
        "use strict";
        var me = this,
            tmpSet = {},
            serchItemComboboxList = Ext.ComponentQuery.query('combobox', me.searchItemPanel);

        for (var i = 0; i < serchItemComboboxList.length; i++){
            var cv = serchItemComboboxList[i].getValue();
            if(tmpSet[cv]){
                return serchItemComboboxList[i];
            } else {
                tmpSet[cv] = true;
            }
        }

        return false;
    },

    onClickEmptySearchItemBtn: function(){
        "use strict";
        var me = this;

        Ext.MessageBox.confirm('提示', '真的要清空吗？', function(buttonId){
            if (buttonId === 'yes'){
                me.searchItemPanel.removeAll();
            }
        });
    },

    makeItemDefaultValueFieldCfg: function(searchGroupItemShip){
        "use strict";
        return Ext.apply({
            itemId: 'itemDefaultValueField',
            name: searchGroupItemShip['entity_field_name'],
            value: searchGroupItemShip['default_value'],
            flex: 1,
            hideLabel: true
        }, convertRawStrToJasn(searchGroupItemShip['item_cfg']));
    },

    onSelectSearchItemCombox: function(combo, records, eOpts){
        "use strict";
        var me = this,
            searchItem,
            itemCfg,
            itemId,
            fieldContainer,
            itemInputCtrl,
            oldItemInputCtrl,
            inputCtrlIdx,
            commonSearchModel = Ext.JwawaResMgr.get('commonSearchModel');

        fieldContainer = combo.up('fieldcontainer');
        itemId = records[0].getId();
        searchItem = commonSearchModel.searchItemStore.getById(itemId);
        itemCfg = me.makeItemDefaultValueFieldCfg(searchItem.data);
        itemInputCtrl = Ext.create(searchItem.get('item_class'), itemCfg);
        oldItemInputCtrl = fieldContainer.down('#itemDefaultValueField');
        inputCtrlIdx = fieldContainer.items.indexOf(oldItemInputCtrl);
        fieldContainer.remove(oldItemInputCtrl);
        fieldContainer.insert(inputCtrlIdx, itemInputCtrl);
    },


    deleteSearchItemContainer: function(btn){
        "use strict";
        var me = this,
            ftcr = btn.up('fieldcontainer'),
            searchItemPanel = me.searchItemPanel;

        searchItemPanel.remove(ftcr);
    }
});